package com.example.homework

import android.os.Bundle
import android.text.TextWatcher
import android.widget.EditText
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.lifecycleScope
import com.example.homework.databinding.ActivityMainBinding
import com.example.homework.viewmodels.MainViewModel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private val viewModel: MainViewModel by viewModels<MainViewModel>()
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.searchButton.setOnClickListener {
            viewModel.searchQuery()
        }
        lifecycleScope.launch {
            launch {
                binding.searchTextInput.textFlow().collect {
                    viewModel.updateInputText(it)
                }
            }
            launch {
                viewModel.uiState.collect {
                    with(binding) {
                        searchButton.isEnabled = it.isButtonEnabled
                        loadingProgressBar.isVisible = it.isProgressBarVisible
                    }
                }
            }
            launch {
                viewModel.queryText.collect {
                    with(binding) {
                        resultTextView.text = getString(R.string.result_text, it)
                    }
                }
            }
        }

    }

    private fun EditText.textFlow(): Flow<String> = callbackFlow {
        val watcher: TextWatcher = doOnTextChanged { text, _, _, _ ->
            trySend(text.toString())
        }
        awaitClose {
            this@textFlow.removeTextChangedListener(watcher)
        }
    }
}